package net.jam.loader;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

import com.sun.org.apache.bcel.internal.classfile.ClassParser;

public class RSLoader extends ClassLoader {
	public HashMap<String, Class<?>> classes = new HashMap<String, Class<?>>();
	JarFile jar = null;

	public RSLoader() throws java.io.IOException {
		jar = downloadRunescapeJar();
	}

	public Class<?> findClass(String name){
		return classes.get(name);
	}

	public Class<?> loadClass(String className) throws ClassNotFoundException {
		System.out.println("LOADING " + className);
		Class<?> c;
		try {
			c = super.findSystemClass(className);
			classes.put(className,c);
			return c;
		} catch (ClassNotFoundException classException) {
			ZipEntry zip = jar.getEntry(className.replaceAll("\\.", "/") + ".class");
			byte[] buffer;
			try {
				buffer = new ClassParser(jar.getInputStream(zip), className).parse().getBytes();
			} catch (IOException e) {
				e.printStackTrace();
				Class<?> classlc = super.loadClass(className);
				classes.put(className,classlc);
				return classlc;
			}
			Class<?> cd = defineClass(className, buffer, 0, buffer.length);
			classes.put(className,cd);
			return cd;
		}
	}

	private JarFile downloadRunescapeJar() {

		File rJar = new File("runescape.jar");

		if(rJar.exists()) {
			if(!rJar.delete()) {
				System.out.println("Failed to remove old runescape.jar");
				return null;
			}
		}
		//   long startTime = System.currentTimeMillis();
		try {
			System.out.print("Downloading runescape.jar\n");   
			JarURLConnection jarUrl =
				(JarURLConnection)new URL("jar:http://world1.runescape.com/runescape.jar!/")
			.openConnection();
			if (jarUrl != null) {
				System.out.println("\rDownloaded runescape.jar succesfully.\n\n");
				return jarUrl.getJarFile();
			}
			
	    /*System.out.print("Downloading runescape.jar Method by Affix\n");
	    URLConnection jarUC;
			     jarUC = new URL("http://world"+Loader.worldID+".runescape.com/runescape.jar").openConnection();
			DataInputStream down = new DataInputStream(jarUC.getInputStream());
            PrintStream out = new PrintStream(rJar);
            double length = jarUC.getContentLength();
            double tempLength = rJar.length();
            int read;
            byte[] buffer = new byte[5000];
            while ((read = down.read(buffer)) > 0)
            	out.write(buffer, 0, read);
            System.out.println("\rDownloaded runescape.jar succesfully.\n\n");
            return new JarFile(rJar);*/
			//return new JarFile(rJar);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
